<template>
  <n-modal
    v-model:show='showModal'
    preset='card'
    title='管理职位的菜单'
    :show-icon='false'
    class='w-800px'
  >
    <!-- 创建和编辑区域 -->
    <mycard v-if="editType === 'add' || editType === 'edit'" class='p-2'>
      <div class='w-full flex justify-start items-center'>
        <n-button-group>
          <n-button @click='allseclct' type='primary'>全选</n-button>
          <n-button @click='noselect'>取消全选</n-button>
          <!--          <n-button @click='shownowlist'>测试</n-button>-->
        </n-button-group>
      </div>
      <n-tree
        ref='treeref'
        block-line
        :data='treeData'
        :checked-keys='selectData'
        :on-update:indeterminate-keys='indeterminateData'
        :on-update:checked-keys='change2'
        key-field='id'
        label-field='name'
        checkable
        cascade
        selectable
      />
    </mycard>
    <!-- 回显区域 -->
    <mycard v-if="editType === 'view'">
      <descriptions :infoList='_infoList'></descriptions>
    </mycard>

    <!-- 交互成功区域 -->
    <mycard v-if="editType === 'success'">
      <n-result status='success' title='成功' :description='resultText'>
      </n-result>
    </mycard>
    <!-- 交互失败区域 -->
    <mycard v-if="editType === 'error'">
      <n-result status='error' title='错误' :description='resultText'>
      </n-result>
    </mycard>
    <template #action>
      <div class='w-full flex justify-end items-center'>
        <n-button class='mx-1' v-if="editType === 'error'" @click='getreturn'
        >返回
        </n-button
        >
        <n-button class='mx-1' @click='handleClose'>关闭</n-button>
        <n-button
          class='mx-1'
          v-if="editType === 'add' || editType === 'edit'"
          type='primary'
          @click='handleSave'
        >确定
        </n-button
        >
      </div>
    </template>
  </n-modal>
</template>


<script setup name='menuEdit' lang='ts'>
import { openAndClose } from '../../../hooks/useEdit'
import { ref, defineExpose, defineEmits, computed } from 'vue'
import { treeToArray } from '../../../util/arraytotree'

const treeref = ref<any>(null) // 表单组件
const formValue = ref<any>({}) // 表单数据
const treeData = ref([])  // 属性数据
const selectData = ref([])   // 选中的数据
const treeArray = ref([]) // 扁平数据
const halfselectData = ref([])
const emit = defineEmits(['close'])
// 自定义重置组件的方法
const reset = () => {
  formValue.value = {}
  treeData.value = []
  selectData.value = []
  treeArray.value = []
  halfselectData.value = []
}
// 自定义初始化需要执行的方法
const chushihua = (data: any) => {
  if (data) {
    formValue.value = data
  }
  gettreeDatefunc()
  getselectData()
}
// 从钩子中结构出需要的函数和属性
const {
  showModal,
  editType,
  resultText,
  init,
  handleClose,
  getsuccess,
  getfaild,
  http, message,
} = openAndClose(chushihua, reset, '', emit)


// 点击确定
const handleSave = () => {
  createfunc()
}

const createfunc = () => {
  const config = {
    menus: [...selectData.value, ...halfselectData.value],
    position: formValue.value.id,
  }
  http.positionMenuadd(config).then((res: any) => {
    if (res.data.code === 0) {
      getsuccess('创建成功')
    }
  }).catch(err => {
    getfaild(err || '创建失败')
  })

}


// 点击返回
const getreturn = () => {
  if (formValue.value.id) {
    editType.value = 'edit'
  } else {
    editType.value = 'add'
  }
  resultText.value = ''
}

// 获取菜单的属性数据
const gettreeDatefunc = () => {
  http.menutree({}).then((res: any) => {
    if (res.data.code == 0) {
      treeData.value = res.data.items
      treeArray.value = treeToArray(treeData.value)
    } else {
      message.error(res.data.error.toString() || '获取菜单数据失败')
    }
  }).catch(err => {
    message.error(err || '查询失败')
  })
}

// 获取已选择数据
const getselectData = () => {
  const config = {
    position: formValue.value.id,
  }
  console.log(config, '参数是什么')
  http.menubyposition(config).then((res: any) => {
    if (res.data.code === 0) {
      selectData.value = res.data.items.map((item:any)=>{
        if(item.fenlei!==3){
          return item.id
        }
      }).filter((item:any)=>item)
    } else {
      message.error(res.data.error.toString() || '获取职位的菜单失败')
    }
  }).catch((err: string) => {
    message.error(err || '获取职位的菜单失败')
  })
}

const infoList = ref([
  { label: '名称', key: 'name' },
  {
    label: '所属上级', key: 'parent', render: (data: any) => {
      return data ? data.name : ''
    },
  },
  {
    label: '创建时间', key: 'createdTime', render: (time: string) => {
      return new Date().toMyString(time)
    },
  },
  {
    label: '更新时间', key: 'changeTime', render: (time: string) => {
      return new Date().toMyString(time)
    },
  },
])
const _infoList = computed(() => {
  return infoList.value.map((item: any) => {
    return { ...item, value: item.render ? item.render(formValue.value[item.key]) : formValue.value[item.key] }
  })
})

// 选中回调
const change2 = (keys: Array<string | number>) => {
  console.log(keys, '现在')
  selectData.value = keys
}
const indeterminateData = (keys: Array<string | number>) => {
  console.log(keys, '半选中')
  halfselectData.value = keys
}
// 点击全选
const allseclct = () => {
  selectData.value = treeArray.value.map(item => item.id)
}
// 取消全选
const noselect = () => {
  selectData.value = []
}
// 测试
const shownowlist = () => {
  console.log(selectData.value)
  console.log(treeref.value, '组件啊')
}

// 抛出属性和方法
defineExpose({ init, handleClose })
</script>

<style scoped>
</style>
